app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "批量插入PDF");

function main() {
    var sel = app.selection;
    if (!sel.length) { alert("请先选中图片框架"); return; }

    var folder = Folder.selectDialog("选择包含PDF文件的文件夹");
    if (!folder) return;

    var pdfs = folder.getFiles("*.pdf");
    if (!pdfs.length) { alert("未找到PDF文件"); return; }

    for (var i = 0; i < sel.length && i < pdfs.length; i++) {
        var f = sel[i];
        if (f.constructor.name !== "Rectangle" && f.constructor.name !== "Polygon" && f.constructor.name !== "Oval") continue;

        try {
            f.place(pdfs[i]);
            f.fit(FitOptions.PROPORTIONALLY);
        } catch (e) {
            $.writeln("无法放置：" + pdfs[i].name + " → " + e);
        }
    }
    alert("完成 " + Math.min(sel.length, pdfs.length) + " 个PDF链接。");
}
